<template>
	<view class="page">
		<view class="position">
			<view class="top_img">
				<image style="max-width: 170rpx;" src="@/static/images/icons/index_top.png" mode="widthFix">
				</image>
				<view class="text f18">
					*每日食品均经资质核验、溯源检查及检测检疫后采购
				</view>
			</view>
			<view class="content">
				<view class="card flex_align_conter profile">
					<!-- <u-avatar :src="avatar" ></u-avatar> -->
					<view style="max-width: 130rpx;max-height: 130rpx;border-radius: 50%;">
						<image style="width: 130rpx;height: 130rpx;border-radius: 50%;"  :src="avatar" mode=""></image>
					</view>
					<view class="" style="margin-left: 32rpx;">
						<view v-if="userInfo.userName" class="" style="font-size: 36rpx;">
							Hi,{{userInfo.userName}}
						</view>
						<view v-else class="" style="font-size: 36rpx;" @click="goLogin">
							Hi,请登录
						</view>
						<view class="" style="font-size: 30rpx;font-weight: 350;color: #848484;margin-top: 16rpx;">
							生活可以平凡，但每一餐都要吃出独特的仪式感
						</view>
					</view>
				</view>
				<view class="card flex_between tow_item" style="margin-bottom: 20rpx;">
					<image style="width: 280rpx;height: 230rpx;" src="@/static/images/icons/index_tow.png"
						mode="widthFix">
					</image>
					<view class="but">
						<button class="login-btn cu-btn block bg-yellow round" @click="goReserve">
							<view class="">
								<view class="f18">
									预约报餐
								</view>
								<view class="f18" style="margin-top: 10rpx;">
									{{nextWeekTime}}
								</view>
							</view>

						</button>
						<view class="f26" style="margin-top: 10rpx;">
							开始美好便捷的用餐体验
						</view>
					</view>
				</view>
			
				<view class="card notice_item flex_between" @click="goNotice">
					<image style="width: 48rpx;" src="@/static/images/icons/notice.svg" mode="widthFix"></image>
					<view class="ellipsisf18" style="width: 460rpx;" v-if="noticeList.length>0">
						{{noticeList[0].noticeContent}}
					</view>
					<myMore></myMore>
				</view>
				<view class="main_con">
					<view class="">
						<view class="flex_between" style="padding-right: 20rpx;">
							<uni-section class="section_b" title="当天餐食" type="line" titleFontSize="36rpx"></uni-section>
							<view class="flex_align_conter">
								<view class="f18" style="display: flex;align-items: center;">
									{{today}}
									<view class="" v-if="today && getDayOfWeek(today)"
										style="margin-top: -5rpx;background-color: #0EB275;color: white;padding: 15rpx 15rpx;font-size: 15px;border-radius: 60rpx 60rpx 0 60rpx;margin-left: 15rpx;">
										{{getDayOfWeek(today)}}
									</view>
								</view>
								<view class="txt" @click="weekNewAdd(item)" style="font-size: 36rpx;">
									新增本周
								</view>
								<!-- <view class="txt" v-if="!isAfter9AM() && clockApproval.configValue == 1"> -->

							</view>
						</view>



						<view class="definite_crad">
							<view class="hint flex_align_conter flex_between" @click="modifyOrder(item)">
								<view @click="modifyOrder(item)"
									style="flex: 8; font-size: 36rpx;display: flex;align-items: center;color: #000000;">
									<uni-icons type="help" size="26"></uni-icons>
									当日00:00-9:00可修改订餐（每人每天限3次）
								</view>
								<view  v-if="homeTodayList.length==0" class="txt" @click="modifyOrder(item)"
									style="font-size: 36rpx;flex: 2;text-align: right;">
									新增
								</view>
							</view>
							<view class="home_today_item" v-for="item in homeTodayList" @click="modifyOrder(item)">
								<view class="flex_between">
									<view class="">
									</view>
									<!-- foodOrder -->
									<view
										style="background-color: #0EB275;color: white;padding: 10rpx 15rpx;font-size: 25rpx;border-radius: 60rpx 60rpx 0 60rpx;"
										class="txt" v-if="item.foodOrder.status != 2">
										修改
									</view>
								</view>
								<view class="" v-if="
								(item.dictDataList.meals1&&item.dictDataList.meals1.comboList&&item.dictDataList.meals1.comboList.length > 0 )||  
								(item.dictDataList.meals1&&item.dictDataList.meals1.comboList&&item.dictDataList.meals1.dishList.length > 0) ||  
								(item.dictDataList.meals2&&item.dictDataList.meals2.comboList&&item.dictDataList.meals2.comboList.length > 0) ||  
								(item.dictDataList.meals2&&item.dictDataList.meals2.comboList&&item.dictDataList.meals2.dishList.length > 0) ">
									<homeToday :homeTodayObj="item.dictDataList" :date="today"></homeToday>
								</view>
							</view>


						</view>
					</view>
				</view>
				
				<view class="flex_between three_item flex_between" style="margin-top: 10rpx;">
					<view class="flex1 flex_center_column card_min" style="margin-right: 20rpx;"
						@click="orderingNotice">
						<image style="width: 60rpx;" src="@/static/images/icons/index_three1.svg" mode="widthFix">
						</image>
						<view class="t f36">
							订餐须知
						</view>
					</view>
					<view class="flex1 flex_center_column card_min" @click="cafeteriaContact">
						<image style="width: 60rpx;" src="@/static/images/icons/index_three2.svg" mode="widthFix">
						</image>
						<view class="t f36">
							联系食堂
						</view>
					</view>
				</view>


				<view class="main_con">
					<view class="flex_between" style="padding-right: 20rpx;">
						<uni-section class="section_b" title="智能推荐" type="line" titleFontSize="36rpx"></uni-section>
					</view>
					<view class="definite_crad">
						<view class="">
							<view class="f18 title">
								相似菜品
							</view>
							<view class="flex_wrap">
								<view class="m-r20 m-b8 often_item" v-for="(item,index) in foodDishesList">
									<similarMeal :availablePreview="true" :item="item" :index="index"></similarMeal>
								</view>
							</view>
						</view>
						<view class="crad_item">
							<view class="f18 title">
								同事常点菜品
							</view>
							<view  style="" v-for="(item,index) in oftenMealList">
								<setMealMini :availablePreview="true" :item="item" :index="index"
									:showRanking="false">
								</setMealMini>
							</view>
						</view>
					</view>

				</view>
				<view class="main_con">
					<view class="flex_between" style="padding-right: 20rpx;">
						<uni-section class="section_b" title="本人订餐统计" type="line" titleFontSize="36rpx"></uni-section>
					</view>
					<statistics :data="selfOftenList"></statistics>
				</view>
			</view>
			<uni-popup ref="contactPopup" type="center" class="">
				<cafeteriaContact :phone="phone"></cafeteriaContact>
			</uni-popup>
			<navigationBar tabbarIndex="0">
			</navigationBar>
		</view>
		<view v-if="mengBan==2" class="ImageView" style="display: felx;flex-direction: column;justify-content: center;">
			<view
				style="flex-direction: column;display: flex;align-items: center;justify-content: center;height: 100%;">
				<image style="width: 20%;max-height: 130rpx;"
					src="https://lingxin1314.oss-cn-beijing.aliyuncs.com/cc854224ff521b77e24c0f54a7c26c6.png" mode="">
				</image>
				<view style="text-align: center; margin-top: 20rpx;">
					<image style="max-width: 30%;max-height: 80rpx;"
						src="https://lingxin1314.oss-cn-beijing.aliyuncs.com/91bfdb53d647bb6784e138b763fb496.png"
						mode="">
					</image>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getHomeTodayAPI,
		getOftenMealAPI,
		getSelfOftenAPI,
		getNoticeListAPI,
		getsameMealAPI,
		getClockApprovalAPI,
		getCbreachdy,
		getClconfigAPI
	} from '@/api/index.js'
	import dayjs from 'dayjs'
	import {
		formatDate,
		isInTimeRange
	} from '@/utils/utils.js'
	import navigationBar from '@/components/common/navigationBar.vue'
	import myMore from '@/components/common/more.vue'
	import setMealMini from '@/components/common/setMealMini.vue'
	import similarMeal from '@/components/common/similarMeal.vue'
	import statistics from '@/components/common/statistics.vue'
	import cafeteriaContact from '@/components/common/cafeteriaContact.vue'
	import homeToday from '@/components/common/homeToday.vue'
	export default {
		name: 'MyHome',
		data() {
			return {
				phone: "",
				now: '',
				timeout: false, //是否超过9点
				clockApproval: {},
				noticeList: [],
				selfOftenList: [], //订餐统计
				oftenMealList: [],
				foodDishesList: [],
				homeTodayObj: {},
				homeTodayList: [],
				userInfo: this.$store.state.user.userInfo,
				nextWeekTime: '',
				today: '',
				countNumber: 0,
				mengBan: uni.getStorageSync('isLoginType')
			}
		},
		components: {
			navigationBar,
			myMore,
			setMealMini,
			statistics,
			cafeteriaContact,
			homeToday,
			similarMeal
		},
		computed: {
			avatar() {
				return this.$store.state.user.avatar
			}
		},
		onLoad() {
			this.nextWeekTime = this.getNextWeekRange()
			// 获取当前时间并格式化
			this.today = dayjs().format('YYYY-MM-DD')
			console.log(uni.getStorageSync('isLoginType'), uni.getStorageSync('storage_data'), 66666666)
			if (uni.getStorageSync('isLoginType') == 1 && !uni.getStorageSync('storage_data')) {
				this.mengBan = 2
				this.$tab.reLaunch('/pages/login')
			}
			// 首次进入员工首页判断是否之前登录过。如果之前登陆过。显示中转页 直接跳转管理员首页  否则会闪员工首页闪屏
			if (uni.getStorageSync('isLoginType') == 2) {
				uni.reLaunch({
					url: '/subpackages/admin/pages/index/index'
				})
			}

			if (!this.$store.state.user.token) return //解决resust.js 首次没有登录报错弹窗问题
			this.getHomeToday()
			this.getOftenMeal()
			this.getSelfOften()
			this.getNoticeList()
			this.getsameMeal() //相似菜品
			this.getClockApproval()
			this.isAfter9AM()
			this.countNum()
			// 获取联系食堂
			this.getConfigPhone()
		},
		methods: {
			weekNewAdd() {
				// if (!isInTimeRange()) {
				// 	// 12
				// 	this.$modal.msg("抱歉，当前订餐时间未开放")
				// 	return
				// }
				this.$tab.reLaunch('/pages/reserve/reserve?type=2')
			},
			async getConfigPhone() {
				const res = await getClconfigAPI(103)
				this.phone = res.data.configValue
				console.log('获取电话---', this.phone)
			},
			// 没有token第一次登录条件下登录
			goLogin() {
				this.$tab.navigateTo('/pages/login')
			},
			getDayOfWeek() {
				const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				const dateStr = this.today
				// 1. 替换 "-" 为 "/"（兼容 iOS/小程序日期解析）
				const normalizedDateStr = dateStr.replace(/-/g, '-');
				console.log(normalizedDateStr)
				let date = new Date(normalizedDateStr);

				console.log(date)
				// 2. 如果日期无效，使用当前日期
				if (isNaN(date.getTime())) {
					date = new Date();
				}

				// 3. 返回 "/周几" 格式
				const dayIndex = date.getDay();
				return days[dayIndex];
			},
			checkDateAndTimeWithDayjs(targetDateStr) {
				const targetDay = dayjs(targetDateStr);
				if (!targetDay.isValid()) {
					return {
						isToday: false,
						isAfter9AM: false,
						error: '无效的日期格式'
					};
				}
				const now = dayjs();
				const isToday = targetDay.isSame(now, 'day');

				let isAfter9AM = false;
				if (isToday) {
					const currentHour = now.hour();
					console.log(currentHour)
					// isAfter9AM = currentHour > 9;
					isAfter9AM = currentHour > 8
				}
				return {
					isToday,
					isAfter9AM
				};
			},
			async countNum() {
				const res = await getCbreachdy(this.userInfo.userId)
				console.log(res.data)
				this.countNumber = res.data
			},
			modifyOrder(item) {
				console.log('item', item)
				const today = new Date(); // 当前日期
				const newDate = today.toLocaleDateString()
				const obj = this.checkDateAndTimeWithDayjs(this.today)

				console.log('新增了', this.$store.state.user.userInfo.alterNum)


				if (obj.isToday && obj.isAfter9AM) {
					return this.$modal.msg('已超过修改时间')
				} else if (obj.isToday && !obj.isAfter9AM) {
					if (this.$store.state.user.userInfo.alterNum >= 3 && this.clockApproval.configValue == 0) {
						return this.$modal.msg('已超过修改次数')
					} 
				}

				if (item === undefined) {
					this.$tab.navigateTo(
						`/subpackages/user/pages/order/amendOrder?date=${this.today}`
					)
					return
				}



				this.$tab.navigateTo(
					`/subpackages/user/pages/order/amendOrder?orderId=${item.foodOrder.orderId}&date=${item.foodOrder.date}&num=${item.foodOrder.num}`
				)
			},
			isAfter9AM() {
				// 判断当前时间是否 >= 今天上午9点
				this.timeout = dayjs().hour() >= 16 //测试使用    正常8点
				return dayjs().hour() >= 16; //测试使用 正常8点
			},
			async getClockApproval() {
				const res = await getClockApprovalAPI('nine.clock.approval')
				this.clockApproval = res.data
			},
			goNotice() {
				this.$tab.navigateTo('/subpackages/user/pages/order/notice')
			},
			// 根据多个值过滤数组
			filterArrayByMultipleValues(arr, field, values) {
				// 检查输入的数组是否有效
				if (!Array.isArray(arr)) {
					console.error('第一个参数必须是数组');
					return [];
				}

				// 检查values是否为数组，如果不是则转为数组
				if (!Array.isArray(values)) {
					values = [values];
					console.warn('第二个参数建议传入数组，已自动转为数组处理');
				}

				// 使用filter方法过滤元素
				return arr.filter(item => {
					// 检查元素是否包含该字段，避免报错
					if (item.hasOwnProperty(field)) {
						// 如果字段值不在要排除的values数组中，则保留
						return !values.includes(item[field]);
					}
					// 对于不包含该字段的元素，默认保留
					return true;
				});
			},
			async getNoticeList() {
				const res = await getNoticeListAPI({
					pageNum: 99,
					pageSize: 1,
					noticeType: '1,2,3,4'
				})
				// if (uni.getStorageSync('isLoginType') == 1) {
				// 	this.noticeList = this.filterArrayByMultipleValues(res.rows, 'noticeType', ['5', '6'])
				// 	console.log('获取消息----------------------',this.noticeList)
				// 	return
				// }
				this.noticeList = res.rows
				console.log('获取消息', this.noticeList)
			},
			async getSelfOften() {
				// let obj = {
				// 	userId: this.userInfo.userId
				// }
				const res = await getSelfOftenAPI()
				this.selfOftenList = res.data
				this.selfOftenList.forEach(item => {
					if (item.listItem) {
						item.dishNameArr = item.listItem.map(item2 => {
							return item2.foodDish.foodName
						})
					}
					item.dishName = item.dishNameArr.join(',')

				})
			},
			groupFoodsByCombo(data) {
				// 检查输入是否为有效的数组
				if (!Array.isArray(data)) {
					return [];
				}

				const result = [];

				// 遍历每个组合
				data.forEach(combo => {
					const {
						price,
						comboName,
						listItem,
						saleAllNum,
						comboId
					} = combo;

					// 跳过没有名称或没有菜品列表的组合
					if (!comboName || !Array.isArray(listItem)) {
						return;
					}

					// 收集当前组合下的所有foodName
					const foodNames = listItem
						.filter(item => item?.foodDish?.foodName) // 过滤有效的菜品
						.map(item => item.foodDish.foodName); // 提取foodName

					// 只添加有菜品的组合
					if (foodNames.length > 0) {
						result.push({
							price,
							id: comboId,
							comboName,
							saleAllNum,
							foodNames
						});
					}
				});

				return result;
			},

			async getOftenMeal() {
				const res = await getOftenMealAPI()
				this.oftenMealList = this.groupFoodsByCombo(res.data.slice(0, 6))
				console.log('获取同事常点菜品', this.oftenMealList)
			},
			async getsameMeal() {
				let obj = {
					type: 1
				}
				const res = await getsameMealAPI(obj)
				this.foodDishesList = res.data.foodDishes ? res.data.foodDishes.slice(0, 6) : []
			},
			async getHomeToday() {
				const res = await getHomeTodayAPI(this.today)
				this.homeTodayList = res.data
				console.log('打印当天餐食----------', this.homeTodayList)

			},
			orderingNotice() {
				this.$tab.navigateTo('/subpackages/user/pages/order/orderingNotice') // orderingNotice
			},
			cafeteriaContact() {
				this.$refs.contactPopup.open() // close()
			},
			goReserve() {
				if (!isInTimeRange()) {
					// 12
					this.$modal.msg("抱歉，当前订餐时间未开放")
					return
				}
				this.$tab.reLaunch('/pages/reserve/reserve')
			},
			getNextWeekRange() {
				const today = dayjs()
				const dayOfWeek = today.day() // 0-6，周日为0，周一为1
				// 本周一
				const thisMonday = today.subtract(dayOfWeek === 0 ? 6 : dayOfWeek - 1, 'day')

				// 下周一和下周日
				const nextMonday = thisMonday.add(7, 'day')
				const nextSunday = nextMonday.add(6, 'day')

				// 输出格式：2025/6/9-6/15
				return `${nextMonday.format('YYYY/M/D')}-${nextSunday.format('M/D')}`
			}



		},
	}
</script>

<style scoped lang="scss">
	.page {
		// height: 100vh;
		background: #F2F2F2;
		padding-bottom: 30rpx;
	}

	.top_img {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 180rpx 40rpx 120rpx;
		width: 100%;
		height: 500rpx;
		background-image: url('https://beihai-food.oss-cn-beijing.aliyuncs.com/02.png');
		background-size: contain;
		background-repeat: no-repeat;
		font-size: 36rpx;
		font-weight: 500;

		.text {
			font-size: 20rpx;
			color: #fff;
		}
	}

	.content {
		position: relative;
		top: -130rpx;
		padding: 40rpx 20rpx;
		// background-color: #bfa;

		.card {
			padding: 0 40rpx;
			width: 100%;
			border-radius: 16rpx;
			background: #FFFFFF;
		}

		.profile {
			height: 180rpx;
			box-shadow: 0px 0px 10px 0px rgba(37, 138, 100, 0.2);
		}

		.tow_item {
			margin-top: 20rpx;
			padding-top: 40rpx;
			height: 194rpx;
			background: linear-gradient(180deg, #E7FFF6 0%, #FFFFFF 42%);
			padding-bottom: 40rpx;

			.but {
				display: flex;
				flex-direction: column;
				align-items: center;
			}

			.login-btn {
				width: 320rpx;
				height: 124rpx;
			}
		}

		.three_item {
			width: 100%;
			height: 180rpx;

			.card_min {
				height: 90px;
				border-radius: 16rpx;
				background: #FFFFFF;

				.t {
					margin-top: 16rpx;
				}
			}
		}

		.notice_item {
			height: 100rpx;
		}

		.main_con {

			.txt {
				margin-left: 18rpx;
				color: $uni-color-primary;
			}

			.definite_crad {
				padding: 24rpx;
				border-radius: 16rpx;
				background: #FFFFFF;

				.crad_item {
					margin-top: 30rpx;
				}

				.title {
					font-weight: 500;
					margin-bottom: 18rpx;
				}
			}

			.section_b {
				background: #F2F2F2;
				font-size: 36rpx;
			}

			.hint {
				// position: absolute;
				// top: 40rpx;
				// right: 20rpx;
				// justify-content: end;
				font-size: 20rpx;
				color: #848484;
			}

			::v-deep .section_b .uni-section {
				background: #F2F2F2;
			}

			::v-deep .section_b .line {
				background: #1BB67C;
			}
		}

		.goods-list {
			margin-bottom: 20rpx;

			.total {
				margin-top: 40rpx;
			}
		}

		// .often_item{
		/* 去除每行第3个元素的右边距 */
		.often_item:nth-child(3n) {
			margin-right: 0;
		}

		// }
		// .uni-section {
		// 	background-color: rgba(0, 0, 0, 0) !important;
		// }
	}

	.home_today_item {
		position: relative;

		.txt {
			position: absolute;
			right: 0;
			top: 10rpx;
			z-index: 2;
		}
	}
</style>